package com.sudo.service.admin.service.impl;

import com.sudo.dao.admin.entity.SysConfig;
import com.sudo.dao.admin.mapper.SysConfigMapper;
import com.sudo.service.admin.service.AdminBaseService;
import com.sudo.service.admin.service.SysConfigService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysConfigServiceImpl extends AdminBaseService implements SysConfigService {
    @Resource
    private SysConfigMapper sysConfigMapper;

    @Override
    public int updateValueByObjectKey(String object, Map<String,String> stringMap) {
        Example example = new Example(SysConfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("_object", object);

        int affectCount = 0;
        for (Map.Entry<String, String> entry : stringMap.entrySet()) {
            criteria.getCriteria().clear();
            criteria.andEqualTo("_key", entry.getKey());

            SysConfig sysConfig = new SysConfig();
            sysConfig.set_value(entry.getValue());
            affectCount += sysConfigMapper.updateByExampleSelective(sysConfig, example);
        }
        return affectCount;
    }

    @Override
    public Map<String,String> getSysConfigMapByObject(String object) {
        Example example = new Example(SysConfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("_object", object);
        List<SysConfig> sysConfigList = sysConfigMapper.selectByExample(example);
        Map<String, String> stringMap = new HashMap<>();
        for (SysConfig config : sysConfigList) {
            stringMap.put(config.get_key(), config.get_value());
        }
        return stringMap;
    }

    @Override
    public SysConfig getSysConfigByObjectKey(String object, String key) {
        Example example = new Example(SysConfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("_object", object);
        criteria.andEqualTo("_key", key);
        return sysConfigMapper.selectOneByExample(example);
    }

    @Override
    public List<SysConfig> getSysConfigListByObject(String object) {
        Example example = new Example(SysConfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("_object", object);
        return sysConfigMapper.selectByExample(example);
    }
}
